<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Response;
use think\Session;
use think\Db;
use think\Exception;
use app\common\library\Email;

class Product extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = 'default';

    private $appid = "wxff36bdb319a343b1";
    private $secret = "119b97d84969b128f32af7384559c917";
    private $mch_id = "1483584142";
    private $key = "asdasdwqwqras12d231da21d12mhqw1e";
    
    public function index()
    {
        return $this->view->fetch();
    }
    public function detail()
    {

        $info = Db::table('fa_warranty')->where(['type'=>$this->request->request('bdtype'),'userName'=>Session::get('userName')])->find(); 
        $this->view->assign('info',$info);  
        if($info['safe_years'] == '1'){ 
            $this->view->assign('year', '一');
        }else{

            $this->view->assign('year', '叁');
        }
        $big_number = $this->request->request('bdtype');
        if($this->request->request('type')){
            $this->view->assign('type', 1);
        }else{
            $this->view->assign('type', 0);
        }
        $this->view->assign('big_number', $big_number);
        if($big_number == 'PZAH202042010000000051(10w)' || $big_number == 'PZAH202042010000000051(15w)' || $big_number == 'PZAH202042010000000051(20w)' || $big_number == 'PZAH202042010000000051(30w)' || $big_number == 'PZAH202042010000000051(40w)'){ 
            return $this->view->fetch('product/pzahdetail');
        }elseif($big_number == 'PZAH201942010000000077(TQ50w)'){
            return $this->view->fetch('product/tq15w'); 
        }elseif($big_number == 'PZAH202042010000000051(NEW 20W)' || $big_number == 'PZAH202042010000000051(NEW 40W)' || $big_number == 'PZAH202042010000000074(20W)' || $big_number == 'PZAH202042010000000074(50W)'  ){
            return $this->view->fetch('product/newdetail'); 
        }
        



        else{  
            return $this->view->fetch();
        }
        // $this->view->assign('safe_year', $this->request->request('safe_year'));
        // $this->view->assign('ctype', $this->request->request('ctype')); 
        return $this->view->fetch();
    } 
    public function buy(){
        if(!Session::get('openid')){ 
            $openid=$this->GetOpenid(); 
        }   
        $this->view->assign('safe_year', $this->request->request('safe_year'));
        $this->view->assign('ctype', $this->request->request('ctype'));
        $this->view->assign('openid', Session::get('openid'));
        $this->view->assign('small_number', $this->getSmallNumber());
        return $this->view->fetch();
    }
    public function getSmallNumber(){
        $where = array();
        $where['small_number'] = ['like','90%'];
        $result = Db::table('fa_order')->where($where)->order('id DESC')->find();
        $small_number = $result['small_number']+1;
        return  $small_number;
        // for ($i=9000001; $i<=9019000 ; $i++) { 
        //     if(!Db::table('fa_order')->where(['small_number'=>$i])->find()){
        //         return $i;
        //         break;
        //     }
        // } 
    }
  	public function getPiccSmallNumber(){
    	$where = array();
        $where['small_number'] = ['like','A0%'];
        $result = Db::table('fa_order')->where($where)->order('small_number DESC')->find();
      	$small_number = str_replace("A","1",$result['small_number']);
      	$small_number = $small_number+1;
        $rt = 'A'.substr($small_number,1,7); 
      	return  $rt;
    }
    public function getPiccNewOneSmallNumber(){
        $where = array();
        $where['small_number'] = ['like','A10%'];
        $result = Db::table('fa_order')->where($where)->order('small_number DESC')->find();
        if($result){
            $small_number = str_replace("A","",$result['small_number']);
        }else{
            $small_number = 1000000;
        } 
        $s = $small_number+1;
        $rt = 'A'.$s; 
        return  $rt;
    }
    public function getPiccNewTreeSmallNumber(){
        $where = array();
        $where['small_number'] = ['like','A11%'];
        $result = Db::table('fa_order')->where($where)->order('small_number DESC')->find();
        if($result){
            $small_number = str_replace("A","",$result['small_number']);
        }else{
            $small_number = 1100000;
        } 
        $s = $small_number+1;
        $rt = 'A'.$s; 
        return  $rt;
    }

    public function getPzahNewTreeSmallNumber(){
        $where = array();
        $where['small_number'] = ['like','A50%'];
        $result = Db::table('fa_order')->where($where)->order('small_number DESC')->find();
        if($result){
            $small_number = str_replace("A","",$result['small_number']);
        }else{
            $small_number = 5000000;
        } 
        $s = $small_number+1;
        $rt = 'A'.$s; 
        return  $rt;
    }
    //途强3年50万
    public function gettuqiangSmallNumber(){
        $where = array();
        $where['small_number'] = ['like','T11%'];
        $result = Db::table('fa_order')->where($where)->order('small_number DESC')->find();
        if($result){
            $small_number = str_replace("T","",$result['small_number']);
        }else{
            $small_number = 11000;
        } 
        $s = $small_number+1;
        $rt = 'T'.$s; 
        return  $rt;
    }
    //新20万一年
    public function getnewoneyear20SmallNumber(){
        $where = array();
        $where['small_number'] = ['like','PZAH51%'];
        $result = Db::table('fa_order')->where($where)->order('small_number DESC')->find();
        if($result){
            $small_number = str_replace("PZAH","",$result['small_number']);
        }else{
            $small_number = 5100000;
        } 
        $s = $small_number+1;
        $rt = 'PZAH'.$s; 
        return  $rt;
    }

    //新20万三年
    public function getnewthreeyear20SmallNumber(){
        $where = array();
        $where['small_number'] = ['like','PZAH74%'];
        $result = Db::table('fa_order')->where($where)->order('small_number DESC')->find();
        if($result){
            $small_number = str_replace("PZAH","",$result['small_number']);
        }else{
            $small_number = 7400000;
        } 
        $s = $small_number+1;
        $rt = 'PZAH'.$s; 
        return  $rt;
    }

    public function addOrderLog($data){
        $data['create_time'] = time();
        return Db::table('fa_order_log')->insert($data); 
    }
    public function active(){  
        if(!Session::get('userName')){ 
            $this->error('登录标识过期，请重新登录');
        }
        $id = $this->request->request('id');
        $info = Db::table('fa_warranty')->where(['id'=>$id])->find(); 
        if($info['num'] == 0){ 
            $this->error('该保单可用数量为0');
        }
        if($this->request->isPost()){ 

            $dd = $this->request->post();
            unset($dd['__token__']); 
            $dd['userName'] = Session::get('userName');
            $dd['out_trade_no'] = date('YmdHis').time();
            $dd['pay_status'] = 1;
            $dd['create_time'] = time(); 
          	if($dd['insurance_company'] == 'PINGAN'){
           	 	$dd['small_number'] = $this->getSmallNumber();
            }else{
                //人保旧3年
                if($dd['big_number'] == 'PZAH201942010000000095'){ 
                    $dd['small_number'] = $this->getPiccSmallNumber();
                }elseif($dd['big_number'] == 'PZAH202042010000000011'){ 
                    $dd['small_number'] = $this->getPiccNewTreeSmallNumber();
                }elseif($dd['big_number'] == 'PZAH202042010000000010'){ 
                    $dd['small_number'] = $this->getPiccNewOneSmallNumber();
                }elseif($dd['big_number'] == 'PZAH202042010000000051(10w)' || $dd['big_number'] == 'PZAH202042010000000051(15w)'|| $dd['big_number'] == 'PZAH202042010000000051(YX15w)' || $dd['big_number'] == 'PZAH202042010000000051(20w)' || $dd['big_number'] == 'PZAH202042010000000051(30w)' ||$dd['big_number'] == 'PZAH202042010000000051(40w)' ||$dd['big_number'] == 'PZAH202042010000000051(NEW 10W)' ){ 
                    $dd['small_number'] = $this->getPzahNewTreeSmallNumber();
                }elseif($dd['big_number'] == 'PZAH201942010000000077(TQ50w)'){ 
                    $dd['small_number'] = $this->gettuqiangSmallNumber();
                }elseif($dd['big_number'] == 'PZAH202042010000000074(50W)' || $dd['big_number'] =='PZAH202042010000000074(20W)'|| $dd['big_number'] =='PZAH202042010000000074(10W)'){ 
                    $dd['small_number'] = $this->getnewthreeyear20SmallNumber();
                }elseif($dd['big_number'] == 'PZAH202042010000000051(NEW 20W)' || $dd['big_number'] =='PZAH202042010000000051(NEW 40W)'){ 
                    $dd['small_number'] = $this->getnewoneyear20SmallNumber();
                }
            } 
            $dd['dj_time'] = strtotime($dd['dj_time']);
            // $dd['buy_time'] = strtotime($dd['buy_time']);
            $dd['buy_time'] = $dd['buy_time']?strtotime($dd['buy_time']):time();
            $dd['beneficiary'] = $dd['beneficiary']?$dd['beneficiary']:$dd['real_name'];
            $res = Db::table('fa_order')->insertGetId($dd);
           
            Db::table('fa_warranty')->where(['id'=>$id])->update(['num'=>$info['num']-1]);

            $this->addOrderLog(['userName'=>Session::get('userName'),'type'=>'激活']);

            if($dd['insurance_company'] == 'PICC'){
                $this->sendEmail($res,$dd['big_number'],$dd['small_number'],$dd['real_name'],'保单激活',$dd['email']);
            } 
            $this->success('激活成功', url('user/mylisthas'));

        }
        $this->view->assign('safe_year', $info['safe_years']);
        $this->view->assign('ctype', $info['insurance_company']);
        $this->view->assign('big_number', $info['type']);
        $this->view->assign('small_number', $this->getSmallNumber());
        return $this->view->fetch();
    }

    //发送邮箱
    private function sendEmail($id,$big_number,$small_number,$name,$type,$email_address){
        \think\Config::set('site', array_merge(\think\Config::get('site'), [])); 
        $email = new Email;
        $html = file_get_contents("http://wx.350gps.cn/index/order/index.html?id={$id}");
        $result = $email
            ->to($email_address)
            ->subject("大保单{$big_number}子保单{$small_number}客户名字{$name}【{$type}】")
            ->message($html)
            ->send(); 
    }



    public function investors(){   
        if($this->request->isPost()){ 
            $dd = $this->request->post();
            unset($dd['__token__']); 
            $dd['userName'] = Session::get('userName')?Session::get('userName'):'散户';
            $dd['out_trade_no'] = date('YmdHis').time();
            $dd['pay_status'] = 0;
            $dd['create_time'] = time(); 
            $dd['dj_time'] = strtotime($dd['dj_time']);
            // $dd['buy_time'] = strtotime($dd['buy_time']);
            $dd['small_number'] = $this->getSmallNumber();
            $dd['buy_time'] = $dd['buy_time']?strtotime($dd['buy_time']):time();
            $dd['beneficiary'] = $dd['beneficiary']?$dd['beneficiary']:$dd['real_name'];
            $res = Db::table('fa_order')->insert($dd); 
            $this->addOrderLog(['userName'=>'散户','type'=>'下单']);
            $this->success('下单成功', url('index/index')); 
        }  
        return $this->view->fetch();
    } 
    public function pay(){  
        $dd = $this->request->post();
        //统一下单接口 
        $t =array();
        $t['appid'] = $this->appid;
        $t['mch_id'] = $this->mch_id;  
        $t['nonce_str'] = rand(100,900).time();
        $t['body'] = "在线充值";
        $t['out_trade_no'] = date('YmdHis').time();
        $t['total_fee'] = $dd['fee']*100;
        $t['spbill_create_ip'] = '192.168.1.1';
        $t['notify_url'] = "http://www.fzjtgps.com/phpinfo.php";
        $t['trade_type'] = "JSAPI";
        $t['openid'] = $this->request->request('openid');
        ksort($t);
        $stringA = $this->ToUrlParams($t)."&key=".$this->key; 
        $t['sign'] = strtoupper(md5($stringA));
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; 
        $tt = $this->ToXml($t);
        $ot =  $this->httppost($url,$tt,'POST'); 
        $ob = (array)simplexml_load_string($ot, 'SimpleXMLElement', LIBXML_NOCDATA);
        try {
            Db::startTrans();
            //保存订单数据
            unset($dd['__token__']); 
            // unset($dd['openid']);   
            $dd['userName'] = Session::get('userName');
            $dd['out_trade_no'] = $t['out_trade_no'];
            $dd['create_time'] = time();
            $dd['dj_time'] = strtotime($dd['dj_time']);
            // $dd['buy_time'] = strtotime($dd['buy_time']);
            $this->addOrderLog(['userName'=>$dd['userName'],'type'=>'支付']);
            $dd['small_number'] = $this->getSmallNumber();
            $dd['buy_time'] = $dd['buy_time']?strtotime($dd['buy_time']):time();
            $dd['beneficiary'] = $dd['beneficiary']?$dd['beneficiary']:$dd['real_name'];
            $res = Db::table('fa_order')->insert($dd);
            Db::commit();
            if($res){ 
                //生成字符串
                $arr = array();  
                $arr['appId'] = $this->appid;
                $arr['timeStamp'] = (string)time();
                $arr['nonceStr'] = rand(100000,900000).time();
                $arr['package'] = "prepay_id=".$ob['prepay_id'];
                $arr['signType'] = "MD5"; 
                ksort($arr);
                $stringB = $this->ToUrlParams($arr)."&key=".$this->key; 
                $arr['paySign'] = strtoupper(md5($stringB)); 
                $result=array('code'=>200,'msg'=>'订单提交成功','data'=>json_encode($arr),'out_trade_no'=>$t['out_trade_no']);
                echo json_encode($result);
                exit;
            }
         } catch (Exception $e) {
             Db::rollback();
             echo json_encode(['code'=>$e->getCode(),'msg'=>$e->getMessage()]);
             exit;
         } 
    }

    public function info(){ 
        $this->layout = '';
        return $this->view->fetch();
    }
    public function payback(){ 
        $out_trade_no = $this->request->request('out_trade_no');
        $result = Db::table('fa_order')->where(['out_trade_no'=>$out_trade_no])->find(); 
        if($result['pay_status']==1){
            $this->success('订单已支付成功', url('user/index'));
        }
        $t =array();
        $t['appid'] = $this->appid;
        $t['mch_id'] = $this->mch_id; 
        $t['out_trade_no'] = $out_trade_no; 
        $t['nonce_str'] = rand(100,900).time(); 
        ksort($t);
        $stringA = $this->ToUrlParams($t)."&key=".$this->key; 
        $t['sign'] = strtoupper(md5($stringA));
        $url = "https://api.mch.weixin.qq.com/pay/orderquery";  
        $tt = $this->ToXml($t); 
        $ot =  $this->httppost($url,$tt,'POST');  
        $ob = (array)simplexml_load_string($ot, 'SimpleXMLElement', LIBXML_NOCDATA);
        if($ob['trade_state']=='SUCCESS'){
            Db::table('fa_order')->where(['out_trade_no'=>$out_trade_no])->update(['pay_status'=>1,'pay_time'=>time()]); 
            $this->success('订单已支付成功', url('user/index'));
        }  
    }
    public function ToXml($data)
    {
        if(!is_array($data) 
            || count($data) <= 0)
        {
            throw new WxPayException("数组数据异常！");
        } 
        $xml = "<xml>";
        foreach ($data as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml; 
    }
        /**
     * 以post方式提交xml到对应的接口url
     * 
     * @param string $xml  需要post的xml数据
     * @param string $url  url
     * @param bool $useCert 是否需要证书，默认不需要
     * @param int $second   url执行超时时间，默认30s
     * @throws WxPayException
     */
       //curl 请求 
    public function httppost($url,  $data = '', $method = 'GET', $json=false){
        $opts = array(
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            // CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'],
            // CURLOPT_FOLLOWLOCATION => 1,
            // CURLOPT_AUTOREFERER => 1,
            // CURLOPT_HEADER => 0,
        ); 
        /* 根据请求类型设置特定参数 */
        $opts[CURLOPT_URL] = $url;     // http_build_query会对特殊字符进行转义
       
        if(strtoupper($method) == 'POST'){
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $data;

            if($json){ //发送JSON数据
                $opts[CURLOPT_HTTPHEADER] = array(
                    'Content-Type: application/json; charset=UTF-8',  
                    'Content-Length: ' . strlen($data),
                );
            }
        }
        // var_dump($opts);
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data  = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch); 
        //发生错误，抛出异常
        if($error) throw new \Exception('请求发生错误：' . $error);
        // FPC($data);
        return  $data;
    }
    public function GetOpenid()
    {
        //通过code获得openid
        if (!isset($_GET['code'])){
            //触发微信返回code码
            $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); 
            $url = $this->__CreateOauthUrlForCode($baseUrl); 
            Header("Location: $url");
            exit();
        } else {
            //获取code码，以获取openid
            $code = $_GET['code']; 
            $openid = $this->GetOpenidFromMp($code);
            Session::set('openid',$openid);
            return $openid;
        }
    }
    public function __CreateOauthUrlForCode($redirectUrl)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_base";
        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);

        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }
    public function GetOpenidFromMp($code)
    {
        $url = $this->__CreateOauthUrlForOpenid($code);
        //初始化curl
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        // if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0" 
        //     && WxPayConfig::CURL_PROXY_PORT != 0){
        //     curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);
        //     curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);
        // }
        //运行curl，结果以jason形式返回
        $res = curl_exec($ch);
        curl_close($ch);
        //取出openid
        $data = json_decode($res,true);
        $this->data = $data; 
        if($data){ 
            $openid = $data['openid'];
        }else{
            $openid = '';
        }
        return $openid;
    }
    private function __CreateOauthUrlForOpenid($code)
    {
        $urlObj["appid"] = $this->appid;
        $urlObj["secret"] = $this->secret;
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        } 
        $buff = trim($buff, "&");
        return $buff;
    }

}
